import { memo } from 'react'

import CommentContext from '../commentConext'
import avatar from '../../assets/images/avatar.png'

/**
 * 日期格式化函数
 * @param {string | Date} date 日期
 */
const formatDate = date => {
  if (typeof date === 'string') return date

  return `${date.getFullYear()}-${
    date.getMonth() + 1
  }-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
}

const ListItem = memo(props => {
  return (
    <div className="list-item">
      <div className="user-face">
        <img className="user-head" src={avatar} alt="" />
      </div>
      <CommentContext.Consumer>
        {value => (
          <div className="comment">
            <div className="user">{props.name}</div>
            <p className="text">{props.comment}</p>
            <div className="info">
              <span className="time">{formatDate(props.createTime)}</span>
              <span
                className={props.isLike ? 'like liked' : 'like'}
                onClick={() => value.dispatch(props.id, 'like')}
              >
                <i className="icon" />
                {props.like !== 0 && <span>{props.like}</span>}
              </span>
              <span
                className={props.isHate ? 'hate hated' : 'hate'}
                onClick={() => value.dispatch(props.id, 'hate')}
              >
                <i className="icon" />
              </span>
              <span className="reply btn-hover">回复</span>
            </div>
          </div>
        )}
      </CommentContext.Consumer>
    </div>
  )
})

export default ListItem
